package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.domain.NewsContent;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.mapper.NewsContentMapper;
import cn.wolfcode.trip.base.mapper.NewsMapper;
import cn.wolfcode.trip.base.query.NewsQuery;
import cn.wolfcode.trip.base.service.INewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NewsServiceImpl implements INewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsContentMapper newsContentMapper;

    @Override
    public PageInfo query(NewsQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrder());
        List<News> list = newsMapper.selectForList(qo);
        return new PageInfo(list);
    }

    /*@Override
    public NewsContent getContentByNewsId(Long newsId) {
        return newsContentMapper.selectByPrimaryKey(newsId);
    }*/

    @Override
    public void saveOrUpdate(News news) {
        if (news.getState() == -1) {
            throw new RuntimeException("请选择是否发布");
        }
        if (news.getId() != null) {
            //更新
            NewsContent content = news.getContent();
            content.setId(news.getId());
            newsMapper.updateByPrimaryKey(news);
            newsContentMapper.updateByPrimaryKey(content);
        } else {
            //新增
            news.setCreateTime(new Date());
            newsMapper.insert(news);
            NewsContent content = news.getContent();
            content.setId(news.getId());
            newsContentMapper.insert(content);
        }
    }

    @Override
    public void changeState(News news) {
        //判断news传入状态
        if (news.getState() == Travel.STATE_RELEASE) {
            news.setReleaseTime(new Date());
        }
        newsMapper.updateState(news);
    }

    @Override
    public NewsContent getNewsContentById(Long newsId) {
        return newsContentMapper.selectByPrimaryKey(newsId);
    }
}
